package com.logic.modular.game.player.match.service.base;

import com.comment.pojo.domain.logic.domain.PvpRanks;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logic.modular.game.core.mapper.PvpRanksMapper;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

import static com.logic.modular.game.GameConstant.PvpRanksCacheKey;

/**
 * 基础服务-武将队伍
 *
 * @author cxy
 * @since 2024-09-11 20:16:33
 */
@Slf4j
@Service
public class PvpRanksBaseServiceImpl extends ServiceImpl<PvpRanksMapper, PvpRanks> {

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;
    @Resource
    private HashOperations<Object, Object, PvpRanks> hashOperations;

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////    转换
    public Map<String, PvpRanks> listToMap(List<PvpRanks> list) {
        return list.stream().collect(Collectors.toMap(
                k -> k.getRankNo().toString(),
                v -> v
        ));
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////  更新插入
    @Override
    public boolean save(PvpRanks entity) {
        boolean save = super.save(entity);
        if (save) {
            savaCache(entity);
        }
        return save;
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////  缓存部分
    public void savaCache(Long keyValue1, Map<String, PvpRanks> map) {
        String key1 = String.format(PvpRanksCacheKey, keyValue1);
        hashOperations.putAll(key1, map);
    }

    public void savaCache(PvpRanks entity) {
        String key1 = String.format(PvpRanksCacheKey, entity.getUid());
        String key2 = entity.getRankNo().toString();
        hashOperations.put(key1, key2, entity);
        redisTemplate.expire(key1, 60, TimeUnit.MINUTES);
    }

    public PvpRanks selectCache(
            @NotNull(message = "keyValue1不能为空") Long keyValue1,
            @NotNull(message = "keyValue2不能为空") Object KeyValue2
    ) {
        String key1 = String.format(PvpRanksCacheKey, keyValue1);
        String key2 = KeyValue2.toString();
        redisTemplate.expire(key1, 60, TimeUnit.MINUTES);
        return hashOperations.get(key1, key2);
    }

    public List<PvpRanks> listCache(
            @NotNull(message = "keyValue1不能为空") Long playerId
    ) {
        String key1 = String.format(PvpRanksCacheKey, playerId);
        redisTemplate.expire(key1, 60, TimeUnit.MINUTES);
        return new ArrayList<>(hashOperations.entries(key1).values());
    }
}
